import math, time
from django.shortcuts import render
from django.conf import settings
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.filters import SearchFilter

# from rest_framework_simplejwt.settings import api_settings
from django_filters.rest_framework import DjangoFilterBackend, FilterSet

from iClouds.Permissions import (
    OR,
    AllPermissions,
    MyPermissions,
    BoxPermissions,
    WeChatPermissions,
    BarPermissions,
)
from iClouds.Authentication import (
    MyJWTAuthentication,
    BoxJWTAuthentication,
    WeChatJWTAuthentication,
    BarJWTAuthentication,
)
from iClouds.mktoken import get_tokens_for_user
from iClouds.apidev import filter_views, has_Random
from iClouds.apidev import redis_key_set

# from iClouds.PulsarSDK import SendAsyncMessage


from . import tasks
from .serializers import *
from .FilterBackends import *

from mysqldb import redis
from mysqldb.reconf import alertConf
from mysqldb.serializers import ListDjangoFilterBackend

from MoniterManager.tasks import doMoniterPulsarScreen


class GetFilterBackend(DjangoFilterBackend):
    """自己定义过滤器"""

    def get_schema_fields(self, view):
        if view.action not in ["list", "retrieve"]:
            return []
        return super().get_schema_fields(view)


class TestViewSet(viewsets.ModelViewSet):
    __title__ = "测试视图"
    __group__ = "门店场所"
    __info__ = {"post": "测试"}
    __doc__ = """
    create:
    <h4>测试</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    # filter_backends = [ListDjangoFilterBackend]
    # filterset_fields = ['pid', 'intetype']

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # r = tasks.CheckWorkItemListAlert()
        # print(r)
        # r = tasks.CheckWorkItemModel()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlaceListSetViewSet(viewsets.ModelViewSet):
    __title__ = "门店场所"
    __group__ = "门店场所"
    __doc__ = """
    create:\n
    <h4>门店场所创建</h4>
        门店场所创建
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayPlaceInfoSerializer  # AllinpayPlaceInfoSerializer  # AllinpayPlaceListSerializer
    queryset = AllinpayPlaceList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(creattime=timezone.now())
        # print(serializer.data)
        # 门店ID
        pid = self.queryset.get(name=serializer.data.get("name")).id
        # 初始化角色
        installRoleConf(pid)
        # 初始化权限-管理员
        ys = [
            i
            for i in range(settings.PLACE_CHMOD_LIST.__len__())
            if 2 in settings.PLACE_CHMOD_LIST[i]
        ]
        rid = AllinpayPlaceroleList.objects.get(pid=pid, name="管理员").id
        lvid = list(AllinpayPlaceviewsList.objects.values_list("id", flat=True))
        rvid = list(
            AllinpayAuthViews.objects.filter(staff__in=ys).values_list("id", flat=True)
        )
        installRolePermConf(rid, lvid)
        installRolePermYunConf(rid, rvid)
        # 初始化员工
        res, faq = AllinpayStaffList.objects.update_or_create(
            defaults={"status": 1}, phone=serializer.data.get("telephone")
        )
        req, faq = AllinpayPlacestaffList.objects.update_or_create(
            defaults={
                "status": 1,
                "created": timezone.now(),
            },
            sid=res.id,
            pid=pid,
        )
        req, faq = AllinpayPlacestaffExtend.objects.update_or_create(
            defaults={
                "mobile": 1,
                "platform": 1,
            },
            id=req.id,
        )
        # 初始化场所员工角色
        AllinpayPlacestaffRole(pid=pid, sid=res.id, rid=rid).save()
        # 初始化收单科目
        AllinpayTermList(name="默认营收", termsn="default", status=1, pid=pid).save()
        # 初始化资产配置
        installHardWareConf(pid)
        # 初始化会员配置
        installMemberConf(pid)
        # 初始化呼叫配置
        installCallmeConf(pid)
        # 初始化场所经营账户
        installBankConf(pid)

        # ...
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlaceInfoSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所信息"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询场所列表",
        "post": "创建场所",
        "patch": "编辑场所",
        "delete": "移除场所",
    }
    __doc__ = """
    list:\n
    <h4>用户信息列表</h4>
        用户信息列表
    retrieve:\n
    <h4>用户信息详情</h4>
        用户信息详情
    partial_update:\n
    <h4>用户信息修改</h4>
        用户信息修改
    """
    http_method_names = ["get", "patch"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlaceInfoSerializer
    queryset = AllinpayPlaceList.objects.all().order_by("-id")
    # GET 条件过滤
    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    filterset_fields = ["auth", "status", "sheng", "shi", "xian", "fee"]
    search_fields = ["name"]

    def list(self, request, *args, **kwargs):
        # 对象级过滤
        # if not request.user.is_super:
        #     xq = AllinpayUserobjectList.objects.filter(uid=request.user.id).values_list(
        #         "pid", flat=True
        #     )
        #     if not xq:
        #         raise serializers.ValidationError({"objectList": "没有场所权限"})
        #     queryset = self.filter_queryset(self.get_queryset().filter(id__in=xq))
        # else:
        #     queryset = self.filter_queryset(self.get_queryset())
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        partial = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 提交变更缓存
        # redis_key_set(instance.id, 1, 60 * 10)
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.id,
        #     "AllinpayPlaceInfo",
        #     f"/place/battrs/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlaceStatusSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所状态"
    __group__ = "门店场所"
    __doc__ = """
    create:\n
    <h4>场所状态修改</h4>
        场所状态修改
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayPlaceStatusSerializer
    queryset = AllinpayPlaceList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.queryset.get(id=serializer.data["id"])
        instance.status = serializer.data.get("status")
        instance.save()
        # 提交变更缓存
        # redis_key_set(instance.id, 1, 60 * 10)
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.id,
        #     "AllinpayPlaceInfo",
        #     f"/place/battrs/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


# class AllinpayPlaceAuthSetViewSet(viewsets.ModelViewSet):
#     __title__ = "场所管理员设置"
#     __group__ = "门店场所"
#     __doc__ = """
#     create:\n
#     <h4>场所管理员修改</h4>
#         场所管理员修改
#     """
#     http_method_names = ["post"]
#     authentication_classes = [MyJWTAuthentication]
#     permission_classes = [MyPermissions]
#     serializer_class = AllinpayPlaceAuthSerializer
#     queryset = AllinpayPlaceList.objects.all()

#     def create(self, request, *args, **kwargs):
#         serializer = self.serializer_class(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         instance = self.queryset.get(id=serializer.data["id"])
#         instance.auth = serializer.data.get("auth")
#         instance.save()
#         # 提交变更缓存
#         # redis_key_set(instance.id, 1, 60 * 10)
#         # 发送消息队列
#         SendAsyncMessage(
#             instance.id,
#             "AllinpayPlaceInfo",
#             f"/place/battrs/{instance.id}/",
#         )
#         return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


class AllinpayPlaceFeeSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所手续费设置"
    __group__ = "门店场所"
    __doc__ = """
    create:\n
    <h4>场所手续费</h4>
        场所手续费
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayPlaceFeeSerializer
    queryset = AllinpayPlaceList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.queryset.get(id=serializer.data["id"])
        instance.fee = serializer.data.get("fee")
        instance.save()
        # 提交变更缓存
        # redis_key_set(instance.id, 1, 60 * 10)
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.id,
        #     "AllinpayPlaceInfo",
        #     f"/place/battrs/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


class AllinpayTermListSetViewSet(viewsets.ModelViewSet):
    __title__ = "经营名目项目"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询经营名目列表",
        "post": "创建经营名目",
        "put": "编辑经营名目",
        "patch": "编辑经营名目",
        "delete": "移除经营名目",
    }
    __doc__ = """
    list:\n
    <h4>经营名目列表</h4>
        经营名目列表
    retrieve:\n
    <h4>经营名目详情</h4>
        经营名目详情
    create:\n
    <h4>经营名目</h4>
        创建经营名目
        termsn  特征码
    partial_update:\n
    <h4>经营名目修改</h4>
        经营名目修改
    """
    http_method_names = ["get", "post", "patch"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayTermListSerializer
    queryset = AllinpayTermList.objects.all()
    # GET 条件过滤
    filter_backends, filterset_fields = [ListDjangoFilterBackend], [
        "pid",
        "termsn",
        "status",
    ]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 提交变更缓存
        # if request.user.id < 1000000 and hasattr(serializer.data, "pid"):
        #     redis_key_set(serializer.data.get("pid"), 1, 60 * 10)
        # 发送消息队列
        # SendAsyncMessage(
        #     serializer.data.get("pid"),
        #     "AllinpayTermList",
        #     f'/place/battrs/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        sess = dict(request.data)
        if "auth" in sess.keys():
            raise serializers.ValidationError({"auth": "该字段禁止编辑"})
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 提交变更缓存
        # if request.user.id < 1000000 and hasattr(instance, "pid"):
        #     redis_key_set(instance.pid, 1, 60 * 10)
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.pid,
        #     "AllinpayTermList",
        #     f"/place/battrs/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayBankListSetViewSet(viewsets.ModelViewSet):
    __title__ = "收款账户"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询收款账户列表",
        "post": "创建收款账户",
        "put": "编辑收款账户",
        "patch": "编辑收款账户",
        "delete": "移除收款账户",
    }
    __doc__ = """
    list:\n
    <h4>收款账户列表</h4>
    retrieve:\n
    <h4>收款账户详情</h4>
    create:\n
    <h4>收款账户创建</h4>
    partial_update:\n
    <h4>收款账户修改</h4>
    """
    http_method_names = ["get", "post", "patch"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayBankListSerializer
    queryset = AllinpayBankList.objects.all()
    # GET 条件过滤
    # filter_backends, filterset_fields = [ListDjangoFilterBackend], ["auth"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     sess.pid,
        #     "AllinpayBankList",
        #     f"/place/battrs/{sess.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayTermBankViewSet(viewsets.ModelViewSet):
    __title__ = "科目绑定账户"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询科目绑定账户列表",
        "post": "创建科目绑定账户",
        "put": "编辑科目绑定账户",
        "patch": "编辑科目绑定账户",
        "delete": "移除科目绑定账户",
    }
    __doc__ = """
    list:\n
    <h4>科目绑定账户列表</h4>
    retrieve:\n
    <h4>科目绑定账户详情</h4>
    create:\n
    <h4>科目绑定账户创建</h4>
    partial_update:\n
    <h4>科目绑定账户修改</h4>
    """
    http_method_names = ["get", "post", "patch"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayTermBankSerializer
    queryset = AllinpayTermBank.objects.all()
    # GET 条件过滤
    # filter_backends, filterset_fields = [ListDjangoFilterBackend], ["auth"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


# class AllinpayUserplaceListSetViewSet(viewsets.ModelViewSet):
#     __title__ = "场所用户"
#     __group__ = "门店场所"
#     __doc__ = """
#     list:\n
#     <h4>场所绑定用户列表</h4>
#         场所绑定用户列表
#     retrieve:\n
#     <h4>场所绑定用户详情</h4>
#         场所绑定用户详情
#     create:\n
#     <h4>场所绑定用户</h4>
#         创建场所绑定用户
#     partial_update:\n
#     <h4>场所绑定用户编辑</h4>
#     delete:\n
#     <h4>场所绑定用户移除</h4>
#         场所绑定用户移除
#     """
#     http_method_names = ["get", "post", "patch", "delete"]
#     authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
#     permission_classes = [MyPermissions | BoxPermissions]
#     serializer_class = AllinpayUserplaceListSerializer
#     queryset = AllinpayUserplaceList.objects.all()
#     # GET 条件过滤
#     filter_backends, filterset_fields = [ListDjangoFilterBackend], ("pid", "uid")

#     def list(self, request, *args, **kwargs):
#         queryset = self.filter_queryset(self.get_queryset())
#         serializer = self.get_serializer(queryset, many=True)
#         return Response({"rescode": 200, "resmsg": serializer.data})

#     def retrieve(self, request, *args, **kwargs):
#         instance = self.get_object()
#         serializer = self.get_serializer(instance)
#         return Response({"rescode": 200, "resmsg": serializer.data})

#     def create(self, request, *args, **kwargs):
#         serializer = self.serializer_class(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response({"rescode": 200, "resmsg": serializer.data})

#     def partial_update(self, request, *args, **kwargs):
#         sess = dict(request.data)
#         if "uid" in sess.keys():
#             raise serializers.ValidationError({"uid": "该字段禁止编辑"})
#         if "pid" in sess.keys():
#             raise serializers.ValidationError({"pid": "该字段禁止编辑"})
#         instance = self.get_object()
#         partial = True
#         serializer = self.get_serializer(instance, data=request.data, partial=partial)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response({"rescode": 200, "resmsg": serializer.data})

#     def destroy(self, request, *args, **kwargs):
#         instance = self.get_object()
#         self.perform_destroy(instance)
#         return Response({"rescode": 200, "resmsg": "SUCCESS"})


# class PlaceUserPermsSetViewSet(viewsets.ModelViewSet):
#     __title__ = "场所员工角色权限设置"
#     __group__ = "门店场所"
#     __doc__ = """
#     create:\n
#     <h4>查询员工角色权限</h4>

#     """
#     http_method_names = ["post"]
#     authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
#     permission_classes = [MyPermissions | BoxPermissions]
#     serializer_class = PlaceUserPermsSerializer
#     queryset = None

#     def create(self, request, *args, **kwargs):
#         serializer = self.serializer_class(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         # serializer.save()
#         return Response({"rescode": 200, "resmsg": serializer.data})


# class PlaceMyUserListViewSet(viewsets.ModelViewSet):
#     __title__ = "场所员工列表查询"
#     __group__ = "门店场所"
#     __doc__ = """
#     create:\n
#     <h4>查询员工角色列表</h4>

#     """
#     http_method_names = ["post"]
#     authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
#     permission_classes = [MyPermissions | BoxPermissions]
#     serializer_class = PlaceMyUserListSerializer
#     queryset = AllinpayUserList.objects.all()

#     def create(self, request, *args, **kwargs):
#         serializer = self.serializer_class(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         # serializer.save()
#         pk = (
#             AllinpayUserplaceList.objects.filter(**serializer.data)
#             .values_list("uid", flat=True)
#             .distinct()
#         )
#         queryset = self.get_queryset().filter(id__in=list(pk))
#         from UserManager.serializers import AllinpayUserListSerializer

#         serializer = AllinpayUserListSerializer(queryset, many=True)
#         return Response({"rescode": 200, "resmsg": serializer.data})


class PlaceLizhuInterfaceSetViewSet(viewsets.ModelViewSet):
    __title__ = "酒店接口"
    __group__ = "门店场所"
    __doc__ = """
    list:\n
    <h4>酒店接口列表</h4>
        酒店接口列表
    retrieve:\n
    <h4>酒店接口信息</h4>
        酒店接口信息
    create:\n
    <h4>酒店接口创建</h4>
        酒店接口创建
    partial_update:\n
    <h4>酒店接口编辑</h4>
    delete:\n
    <h4>酒店接口移除</h4>
        酒店接口移除
    """
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = PlaceLizhuInterfaceSerializer
    queryset = PlaceLizhuInterface.objects.all()
    # GET 条件过滤
    filter_backends, filterset_fields = [ListDjangoFilterBackend], ("pid",)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     serializer.data.get("pid"),
        #     "PlaceLizhuInterface",
        #     f'/place/clizhu/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        sess = dict(request.data)
        if "pid" in sess.keys():
            raise serializers.ValidationError({"pid": "该字段禁止编辑"})
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.pid,
        #     "PlaceLizhuInterface",
        #     f"/place/clizhu/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        pid = instance.pid
        pk = instance.id
        self.perform_destroy(instance)
        # 发送消息队列
        # SendAsyncMessage(pid, "PlaceLizhuInterface", pk, act="delete")
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class PlacePospalInterfaceSetViewSet(viewsets.ModelViewSet):
    __title__ = "商超接口"
    __group__ = "门店场所"
    __doc__ = """
    list:\n
    <h4>商超接口列表</h4>
        商超接口列表
    retrieve:\n
    <h4>商超接口信息</h4>
        商超接口信息
    create:\n
    <h4>商超接口创建</h4>
        商超接口创建
    partial_update:\n
    <h4>商超接口编辑</h4>
    delete:\n
    <h4>商超接口移除</h4>
        商超接口移除
    """
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = PlacePospalInterfaceSerializer
    queryset = PlacePospalInterface.objects.all()
    # GET 条件过滤
    filter_backends, filterset_fields = [ListDjangoFilterBackend], ("pid",)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        sess = dict(request.data)
        if "pid" in sess.keys():
            raise serializers.ValidationError({"pid": "该字段禁止编辑"})
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class PlaceAlertTokenSetViewSet(viewsets.ModelViewSet):
    __title__ = "请求语音token"
    __group__ = "门店场所"
    __doc__ = """
    create:\n
    <h4>请求语音token</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        BarJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BoxPermissions | BarPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        x = alertConf().to_json()
        if not x.get("status"):
            return Response({"rescode": 404, "resmsg": "语音合成未启用"})
        r = redis.new_has_key("sysconf", "AlertToken")
        if not r:
            r, t = tasks.CreateToken(x)
            if r:
                out = t - math.ceil(time.time())
                redis.new_put_key("sysconf", "AlertToken", r, out - 10)
        return Response({"rescode": 200, "resmsg": r})


class AllinpayBoxRegisterSetViewSet(viewsets.ModelViewSet):
    __title__ = "盒子注册"
    __group__ = "门店场所"
    __doc__ = """
    create:\n
    <h4>盒子注册</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayBoxRegisterSerializer
    queryset = AllinpayBoxRegister.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        AllinpayBoxRegister.objects.update_or_create(
            defaults={
                "hash": serializer.data["hash"],
                "creattime": timezone.now(),
            },
            id=serializer.data["id"],
        )
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayBoxLoginSetViewSet(viewsets.ModelViewSet):
    __title__ = "盒子登录"
    __group__ = "门店场所"
    __doc__ = """
    create:\n
    <h4>盒子登录</h4>
        场所端系统自动调用该接口。
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayBoxLoginSerializer
    queryset = AllinpayBoxRegister.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            placeID = AllinpayBoxRegister.objects.get(hash=serializer.data["hash"])
            placeDB = AllinpayPlaceList.objects.get(id=placeID.id)
        except BaseException as err:
            raise serializers.ValidationError({"hash": "场所不存在"})
        if not placeDB.status:
            raise serializers.ValidationError({"place": "场所已锁定"})
        # 创建token
        token = get_tokens_for_user(placeDB)
        # 记录登录时间
        placeID.logintime = timezone.now()
        placeID.save()
        return Response(
            {
                "rescode": 200,
                "token": token["access"],
                "expire": 3600 * 24 - 30,
            }
        )


class AllinpayPlacecorpListSetViewSet(viewsets.ModelViewSet):
    __title__ = "公司连锁列表"
    __group__ = "门店场所"
    __info__ = {"get": "查询公司连锁列表和详情", "post": "创建连锁公司", "patch": "编辑连锁公司"}
    __doc__ = """
    list:\n
    <h4>公司连锁列表</h4>
    retrieve:\n
    <h4>公司连锁详情</h4>
    create:\n
    <h4>创建连锁公司</h4>
    partial_update:\n
    <h4>连锁公司编辑</h4>
    """
    http_method_names = ["get", "post", "patch"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlacecorpListSerializer
    queryset = AllinpayPlacecorpList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["addre", "status"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 创建员工
        res, faq = AllinpayStaffList.objects.update_or_create(
            defaults={"status": 1}, phone=serializer.data.get("phone")
        )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # if request.data.get("status"):
        #     raise serializers.ValidationError({"status": "禁止编辑该字段"})
        if request.data.get("created"):
            raise serializers.ValidationError({"created": "禁止编辑该字段"})
        if request.data.get("modifed"):
            raise serializers.ValidationError({"modifed": "禁止编辑该字段"})
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        instance.modified = timezone.now()  # 编辑时间
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlaceroleListSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所角色列表"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询场所角色列表和详情",
        "post": "创建场所角色",
        "patch": "编辑场所角色",
        "delete": "移除场所角色",
    }
    __doc__ = """
    list:\n
    <h4>场所角色列表</h4>
    retrieve:\n
    <h4>场所角色详情</h4>
    create:\n
    <h4>创建场所角色</h4>
    partial_update:\n
    <h4>场所角色编辑</h4>
    delete:\n
    <h4>场所角色移除</h4>
    """
    http_method_names = ["get", "patch", "post", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlaceroleListSerializer
    queryset = AllinpayPlaceroleList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     serializer.data.get("pid"),
        #     "AllinpayPlaceroleList",
        #     f'/place/myrole/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # if request.data.get("status"):
        #     raise serializers.ValidationError({"status": "禁止编辑该字段"})
        if request.data.get("created"):
            raise serializers.ValidationError({"created": "禁止编辑该字段"})
        if request.data.get("modifed"):
            raise serializers.ValidationError({"modifed": "禁止编辑该字段"})
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.pid,
        #     "AllinpayPlaceroleList",
        #     f"/place/myrole/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        pid = instance.pid
        pk = instance.id
        # 移除员工角色
        AllinpayPlacestaffRole.objects.filter(rid=instance.id).delete()
        # 移除角色权限
        AllinpayPlacerolePerm.objects.filter(rid=instance.id).delete()
        # 移除角色
        self.perform_destroy(instance)
        # 发送消息队列
        # SendAsyncMessage(pid, "AllinpayPlaceroleList", pk, act="delete")
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlacestaffListSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所员工列表"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询场所员工列表和详情",
        "post": "添加场所员工",
        "patch": "编辑在职状态",
        "delete": "员工离职",
    }
    __doc__ = """
    list:\n
    <h4>场所员工列表</h4>
    retrieve:\n
    <h4>场所员工详情</h4>
        <id>:绑定记录ID
    create:\n
    <h4>创建场所员工</h4>
    partial_update:\n
    <h4>场所员工编辑在职状态</h4>
        <id>:绑定记录ID
    delete:\n
    <h4>场所员工离职</h4>
        <id>:绑定记录ID
    """
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlacestaffListSerializer
    queryset = AllinpayPlacestaffList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "sid", "status"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 创建扩展信息
        res, faq = AllinpayPlacestaffExtend.objects.update_or_create(
            defaults={"mobile": 1, "platform": 1}, id=serializer.data.get("id")
        )

        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # if request.data.get("status"):
        #     raise serializers.ValidationError({"status": "禁止编辑该字段"})
        # if request.data.get("created"):
        #     raise serializers.ValidationError({"created": "禁止编辑该字段"})
        # if request.data.get("modifed"):
        #     raise serializers.ValidationError({"modifed": "禁止编辑该字段"})
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        # instance.modifed = timezone.now()  # 编辑时间
        # instance.current = timezone.now()  # 编辑时间
        serializer = self.get_serializer(
            instance, data={"status": request.data.get("status")}, partial=partial
        )
        serializer.is_valid(raise_exception=True)
        serializer.save(modifed=timezone.now())
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.pid,
        #     "AllinpayPlacestaffList",
        #     f"/staff/allstaff/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        """仅离职，非删除数据"""
        instance = self.get_object()
        partial = True
        # instance.modifed = timezone.now()  # 编辑时间
        # instance.status = 0  # 编辑时间
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(modifed=timezone.now(), status=0)
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.pid,
        #     "AllinpayPlacestaffList",
        #     f"/staff/allstaff/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlaceviewsListSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所视图列表"
    __group__ = "门店场所"
    __info__ = {"get": "查询场所视图列表和详情", "post": "创建视图列表"}
    __doc__ = """
    list:\n
    <h4>场所视图列表</h4>
    retrieve:\n
    <h4>场所视图详情</h4>
    create:\n
    <h4>创建视图列表</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlaceviewsListSerializer
    queryset = AllinpayPlaceviewsList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["act"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = AllinpayPlaceviewsCreatSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 取数据
        name = serializer.data.get("name")
        info = serializer.data.get("info")
        act = serializer.data.get("act")
        try:
            sess = AllinpayPlaceviewsList.objects.get(name=name, act=act)
        except BaseException as err:
            res = AllinpayPlaceviewsList(**serializer.data)
            res.save()
        else:
            res, faq = AllinpayPlaceviewsList.objects.update_or_create(
                defaults=serializer.data, id=sess.id
            )
        # 发送消息队列
        # pid = AllinpayPlaceList.objects.filter(status=1).values_list("id", flat=True)
        # [
        #     SendAsyncMessage(
        #         i,
        #         "AllinpayPlacestaffList",
        #         f"/place/myviews/{res.id}//",
        #     )
        #     for i in list(pid)
        # ]
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayAuthviewsListYunSetViewSet(viewsets.ModelViewSet):
    __title__ = "云端视图列表"
    __group__ = "门店场所"
    __info__ = {"get": "查询云端视图列表和详情"}
    __doc__ = """
    list:\n
    <h4>云端视图列表</h4>
        staff = 0; 后台权限范围
        staff = 1; 移动端权限范围
        staff = 2; 场所端权限范围
    retrieve:\n
    <h4>云端视图详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlaceviewsListYunSerializer
    queryset = AllinpayAuthViews.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["staff"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlacestaffRoleSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所员工角色"
    __group__ = "门店场所"
    __info__ = {"get": "查询场所员工角色列表和详情", "post": "绑定场所员工角色", "delete": "移除场所员工角色"}
    __doc__ = """
    list:\n
    <h4>场所员工角色列表</h4>
    retrieve:\n
    <h4>场所员工角色详情</h4>
    create:\n
    <h4>场所员工角色绑定</h4>
    delete:\n
    <h4>场所员工角色移除</h4>
    """
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlacestaffRoleSerializer
    queryset = AllinpayPlacestaffRole.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "sid", "rid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     serializer.data.get("pid"),
        #     "AllinpayPlacestaffRole",
        #     f'/place/staffrole/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        pid = instance.pid
        pk = instance.id
        self.perform_destroy(instance)
        # 发送消息队列
        # SendAsyncMessage(pid, "AllinpayPlacestaffRole", pk, "delete")
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlacerolePermSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所角色场所权限"
    __group__ = "门店场所"
    __info__ = {"get": "查询场所角色场所权限列表和详情", "post": "绑定场所角色场所权限", "delete": "移除场所角色场所权限"}
    __doc__ = """
    list:\n
    <h4>场所角色场所权限列表</h4>
    retrieve:\n
    <h4>场所角色场所权限详情</h4>
    create:\n
    <h4>场所角色场所权限绑定</h4>
    delete:\n
    <h4>场所角色场所权限移除</h4>
    """
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlacerolePermSerializer
    queryset = AllinpayPlacerolePerm.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["vid", "rid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # try:
        #     r = AllinpayPlaceroleList.objects.get(id=serializer.data.get("rid"))
        # except BaseException as err:
        #     pass
        # else:
        #     SendAsyncMessage(
        #         r.pid,
        #         "AllinpayPlacerolePerm",
        #         f'/place/roleperms/{serializer.data.get("id")}/',
        #     )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        # 发送消息队列
        # try:
        #     r = AllinpayPlaceroleList.objects.get(id=instance.rid)
        # except BaseException as err:
        #     pass
        # else:
        #     SendAsyncMessage(
        #         r.pid,
        #         "AllinpayPlacerolePerm",
        #         f"/place/roleperms/{r.id}/",
        #         act="delete",
        #     )
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlacerolePermYunSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所角色云端权限"
    __group__ = "门店场所"
    __info__ = {"get": "查询场所角色云端权限列表和详情", "post": "绑定场所角色云端权限", "delete": "移除场所角色云端权限"}
    __doc__ = """
    list:\n
    <h4>场所角色云端权限列表</h4>
    retrieve:\n
    <h4>场所角色云端权限详情</h4>
    create:\n
    <h4>场所角色云端权限绑定</h4>
    delete:\n
    <h4>场所角色云端权限移除</h4>
    """
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlacerolePermYunSerializer
    queryset = AllinpayPlacerolePermYun.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["vid", "rid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlacestaffExtendSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所员工扩展信息"
    __group__ = "门店场所"
    __info__ = {"get": "查询场所员工扩展信息列表和详情", "patch": "编辑场所员工扩展信息"}
    __doc__ = """
    list:\n
    <h4>场所员工扩展信息列表</h4>
    retrieve:\n
    <h4>场所员工扩展信息详情</h4>
    partial_update:\n
    <h4>编辑场所员工扩展信息</h4>
    """
    http_method_names = ["get", "patch"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlacestaffExtendSerializer
    queryset = AllinpayPlacestaffExtend.objects.all()

    # filter_backends = [ListDjangoFilterBackend]
    # filterset_fields = ["vid", "rid"]
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        instance.modifed = timezone.now()  # 编辑时间
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # try:
        #     r = AllinpayPlacestaffList.objects.get(id=instance.id)
        # except BaseException as err:
        #     pass
        # else:
        #     SendAsyncMessage(
        #         r.pid,
        #         "AllinpayPlacestaffExtend",
        #         f"/place/staffextd/{instance.id}/",
        #     )
        return Response({"rescode": 200, "resmsg": serializer.data})


# class AllinpayPlaceAllTermSetViewSet(viewsets.ModelViewSet):
#     __title__ = "营收特征码列表"
#     __group__ = "门店场所"
#     __info__ = {"post": "查询营收特征码列表和详情"}
#     __doc__ = """
#     create:\n
#     <h4>查询营收特征码列表和详情</h4>

#     """
#     http_method_names = ["post"]
#     authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
#     permission_classes = [MyPermissions | BoxPermissions]
#     serializer_class = NoneSerializer
#     queryset = None

#     def create(self, request, *args, **kwargs):
#         # serializer = self.serializer_class(data=request.data)
#         # serializer.is_valid(raise_exception=True)
#         # serializer.save()
#         return Response({"rescode": 200, "resmsg": settings.ALL_TERMSN_ITEMS})


class AllinpayPlaceStaffPostSetViewSet(viewsets.ModelViewSet):
    __title__ = "员工在岗列表"
    __group__ = "门店场所"
    __info__ = {"get": "查询员工在岗列表和详情", "put": "编辑员工在岗详情"}
    __doc__ = """
    list:\n
    <h4>查询员工在岗列表</h4>
    retrieve:\n
    <h4>查询员工在岗详情</h4>
    update:\n
    <h4>编辑员工在岗详情</h4>
    """
    http_method_names = ["get", "put"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlaceStaffPostSerializer
    queryset = AllinpayPlacestaffPost.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True

        try:
            instance = self.get_object()
        except BaseException as err:
            raise serializers.ValidationError({"pk": "查询员工在岗异常"})

        try:
            Staff = AllinpayPlacestaffList.objects.get(status=1, id=instance.id)
        except BaseException as err:
            if request.data.get("status") == 1:
                raise serializers.ValidationError({"status": "未在职员工不能上岗"})

        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(current=timezone.now())

        # 发送消息队列 Pulsar
        # try:
        #     r = AllinpayPlacestaffList.objects.get(id=instance.id)
        # except BaseException as err:
        #     pass
        # else:
        #     SendAsyncMessage(
        #         r.pid,
        #         "AllinpayPlacestaffPost",
        #         f"/place/staffpost/{instance.id}/",
        #     )
        # 发送消息队列 Pulsar
        # tasks.SendAsyncMessage(Staff.pid, {"status":8,"localhost":"","info":{"name":instance.id,"message":serializer.data.get("status")}})

        from MoniterManager.tasks import doPostEvent

        res = doPostEvent.apply_async((instance.id,))
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRawardModelSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所奖励模板"
    __group__ = "门店场所"
    __info__ = {"get": "查询场所奖励模板列表和详情", "post": "场所奖励模板创建", "put": "场所奖励模板编辑"}
    __doc__ = """
    list:\n
    <h4>场所奖励模板列表</h4>
    retrieve:\n
    <h4>场所奖励模板详情</h4>
    update:\n
    <h4>场所奖励模板编辑</h4>
    create:\n
    <h4>场所奖励模板创建</h4>
    """
    http_method_names = ["get", "post", "put"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayRawardModelSerializer
    queryset = AllinpayRawardModel.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "status"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRawardListSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所奖励分值"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询场所奖励分值列表和详情",
        "post": "场所奖励分值创建",
        "put": "场所奖励分值编辑",
        "delete": "场所奖励分值移除",
    }
    __doc__ = """
    list:\n
    <h4>场所奖励分值列表</h4>
    retrieve:\n
    <h4>场所奖励分值详情</h4>
    update:\n
    <h4>场所奖励分值编辑</h4>
    create:\n
    <h4>场所奖励分值创建</h4>
    delete:\n
    <h4>场所奖励分值移除</h4>
    """
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayRawardListSerializer
    queryset = AllinpayRawardList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "intetype", "raid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        # print(request.data)
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        instance = self.get_object()

        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlaceinterConfViewSet(viewsets.ModelViewSet):
    __title__ = "场所积分兑换配置"
    __group__ = "门店场所"
    __info__ = {
        "get": "场所积分兑换配置查询",
        "post": "场所积分兑换配置创建",
        "put": "场所积分兑换配置编辑",
        "delete": "场所积分兑换配置移除",
    }
    __doc__ = """
    list:\n
    <h4>场所积分兑换配置列表</h4>
    retrieve:\n
    <h4>场所积分兑换配置详情</h4>
        {id} 记录ID
    create:\n
    <h4>场所积分兑换配置创建</h4>
    update:\n
    <h4>场所积分兑换配置编辑</h4>
        {id} 记录ID
    delete:\n
    <h4>场所积分兑换配置移除</h4>
        {id} 记录ID
    """
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BoxPermissions | WeChatPermissions]
    serializer_class = AllinpayPlaceinterConferializer
    queryset = AllinpayPlaceinterConf.objects.all()
    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "intetype"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(currentime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        print(request.data)
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(currentime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlacecameraListSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所监控列表"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询场所监控列表和详情",
        "post": "场所监控创建",
        "put": "场所监控编辑",
        "delete": "场所监控移除",
    }
    __doc__ = """
    list:\n
    <h4>场所监控列表</h4>
    retrieve:\n
    <h4>场所监控详情</h4>
    update:\n
    <h4>场所监控编辑</h4>
    create:\n
    <h4>场所监控创建</h4>
    delete:\n
    <h4>场所监控移除</h4>
    """
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlacecameraListSerializer
    queryset = AllinpayPlacecameraList.objects.all()
    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    filterset_fields = ["pid", "status"]
    search_fields = ["model", "name", "ipadd"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlaceWorkitemViewSet(viewsets.ModelViewSet):
    __title__ = "场所工作项模板列表"
    __group__ = "门店场所"
    __info__ = {
        "get": "场所工作项模板列表",
        "post": "场所工作项模板创建",
        "put": "场所工作项模板编辑",
        "delete": "场所工作项模板移除",
    }
    __doc__ = """
    list:\n
    <h4>场所工作项模板列表</h4>
    retrieve:\n
    <h4>场所工作项模板详情</h4>
    create:\n
    <h4>场所工作项模板创建</h4>
        创建工作项模板
    `每天23:00启动模板自动创建第二天的具体工作项事务`
    `每天00:10启动事务检测昨天未提交的工作项事务`
    update:\n
    <h4>场所工作项模板编辑</h4>
    delete:\n
    <h4>场所工作项模板移除</h4>
    """
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayPlaceWorkitemSerializer
    queryset = AllinpayPlaceworkitemModel.objects.all()
    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    filterset_fields = ["pid", "types", "status"]
    search_fields = ["title"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlaceWorkitemListViewSet(viewsets.ModelViewSet):
    __title__ = "场所工作项事务列表"
    __group__ = "门店场所"
    __info__ = {"get": "场所工作项事务列表", "post": "场所工作项事务创建", "put": "场所工作项事务编辑"}
    __doc__ = """
    list:\n
    <h4>场所工作项事务列表</h4>
    retrieve:\n
    <h4>场所工作项事务详情</h4>
    create:\n
    <h4>场所工作项事务创建</h4>
        创建临时工作项事务
    update:\n
    <h4>场所工作项事务编辑</h4>
    delete:\n
    <h4>场所工作项事务移除</h4>
    """
    http_method_names = ["get", "post", "put"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BoxPermissions | WeChatPermissions]
    serializer_class = AllinpayPlaceworkitemListSerializer
    queryset = AllinpayPlaceworkitemList.objects.all()
    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    # filterset_fields = ["pid", "types", "currentdate"]
    filterset_class = AllinpayPlaceWorkitemListFilterSet
    search_fields = ["title"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # try:
        #     # 创建提醒
        #     tasks.ManualAddTaskAlert(serializer.data)
        #     tasks.CheckWorkItemAlert(serializer.data.get("id"))
        # except BaseException as err:
        #     print(err)
        #     pass
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.currentdate <= date.today():
            raise serializers.ValidationError({"workitemlist.currentdate": "该工作项已锁定"})
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.currentdate <= date.today():
            raise serializers.ValidationError({"workitemlist.currentdate": "该工作项已锁定"})
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


# class AllinpayPlaceWorkitemToModelsViewSet(viewsets.ModelViewSet):
#     __title__ = "从事务创建模板"
#     __group__ = "门店场所"
#     __info__ = {"put": "从事务创建模板"}
#     __doc__ = """
#     update:\n
#     <h4>从事务创建模板</h4>
#         {id} 场所工作项事务记录ID
#     """
#     http_method_names = ["put"]
#     authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
#     permission_classes = [MyPermissions | BoxPermissions]
#     serializer_class = NoneSerializer
#     queryset = AllinpayPlaceworkitemList.objects.all()

#     def update(self, request, *args, **kwargs):
#         instance = self.get_object()
#         serializer = AllinpayPlaceworkitemListSerializer(instance)
#         # 序列化模板
#         res = AllinpayPlaceWorkitemSerializer(data=serializer.data)
#         res.is_valid(raise_exception=True)
#         print(res.data)
#         res.save(status=0)
#         return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayWorkitenTypesViewSet(viewsets.ModelViewSet):
    __title__ = "工作项类型"
    __group__ = "门店场所"
    __info__ = {"get": "工作项类型列表或详情", "post": "创建工作项类型", "put": "编辑工作项类型"}
    __doc__ = """
    list:\n
    <h4>工作项类型列表</h4>
    retrieve:\n
    <h4>工作项类型详情</h4>
        {id} 记录ID
    create:\n
    <h4>门工作项类型创建</h4>
    update:\n
    <h4>工作项类型编辑</h4>
        {id} 记录ID
    """
    http_method_names = ["get", "post", "put"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayWorkitenTypesSerializer
    queryset = AllinpayWorkitenTypes.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlaceWorkitemFromModelsViewSet(viewsets.ModelViewSet):
    __title__ = "从场所模板创建事务"
    __group__ = "门店场所"
    __info__ = {"put": "从场所模板创建事务"}
    __doc__ = """
    update:\n
    <h4>从场所模板创建事务</h4>
        {id} 场所工作项模板记录ID
    """
    http_method_names = ["put"]
    authentication_classes = (
        [] if settings.DEBUG else [MyJWTAuthentication, BoxJWTAuthentication]
    )
    permission_classes = (
        [AllPermissions] if settings.DEBUG else [MyPermissions | BoxPermissions]
    )
    serializer_class = NoneSerializer
    queryset = AllinpayPlaceworkitemModel.objects.all()

    def update(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        # 调用计划任务
        # from .tasks import CheckWorkItemModel, CheckWorkItemList

        # r = tasks.CheckWorkItemModel.apply_async((pk,))
        r = tasks.CheckWorkItemModel.apply_async(kwargs={"wid": pk}).task_id
        # CheckWorkItemList()
        return Response({"rescode": 200, "resmsg": r})


class AllinpayPlaceworkitemSubmitViewSet(viewsets.ModelViewSet):
    __title__ = "工作项事务提交"
    __group__ = "门店场所"
    __info__ = {"post": "工作项事务提交"}
    __doc__ = """
    create:\n
    <h4>工作项事务提交</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BoxPermissions | WeChatPermissions]
    serializer_class = AllinpayPlaceworkitemSubmitSerializer
    queryset = AllinpayPlaceworkitemSubmit.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(currentime=timezone.now())
        # 超时积分
        from StaffManager.staffSDK import addInter

        try:
            w = AllinpayPlaceworkitemList.objects.get(id=serializer.data.get("wid"))
            s = AllinpayPlacestaffList.objects.get(pid=w.pid, sid=w.onstaff)
        except BaseException as err:
            x = False
        else:
            if w.isout and w.over < datetime.now().time():
                x = addInter(s.id, w.outtype, w.outinter, "工作项超时", w.id)
                w.outtype = 1
            else:
                x = False
                w.outtype = 0
            w.save()

        # # 发送微信消息通知
        # from mysqldb.tasks import WeAppsUniformSend
        # r = WeAppsUniformSend.apply_async(
        #     (
        #         "ojs6x5MceRVdWPzY2Jh6fnXKw6CI",
        #         "LoginBefor/callOrder/callOrder",
        #         "收到客户新订单通知",
        #         [
        #             "Test1234567891",
        #             "呼叫订单",
        #             "测试网吧01" + ":" + "019",
        #             "2023-12-12 00:12:12",
        #         ],
        #     )
        # )
        # 发送微信消息通知 Pulsar
        from MoniterManager.tasks import doWorkItemEvent

        res = doWorkItemEvent.apply_async((w.id,))
        return Response({"rescode": 200, "resmsg": serializer.data, "outtime": x})


class AllinpayPlaceworkitemCheckViewSet(viewsets.ModelViewSet):
    __title__ = "工作项事务点检"
    __group__ = "门店场所"
    __info__ = {"get": "查询工作项事务", "post": "工作项事务点检"}
    __doc__ = """
    list:\n
    <h4>工作项事务列表所有</h4>
    retrieve:\n
    <h4>工作项事务详情所有</h4>
    create:\n
    <h4>工作项事务点检</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BoxPermissions | WeChatPermissions]
    serializer_class = AllinpayPlaceworkitemCheckSerializer
    queryset = AllinpayPlaceworkitemCheck.objects.all()

    # serializer_class = AllinpayPlaceworkitemCheckSerializer
    # queryset = AllinpayPlaceworkitemCheck.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = AllinpayPlaceworkitemCheckSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(currentime=timezone.now())
        # 派发积分
        from StaffManager.staffSDK import addInter

        try:
            w = AllinpayPlaceworkitemList.objects.get(id=serializer.data.get("wid"))
            s = AllinpayPlacestaffList.objects.get(pid=w.pid, sid=w.onstaff)
            # sw = AllinpayPlaceworkitemListSerializer(w).data
        except BaseException as err:
            x = False
        else:
            x = addInter(s.id, w.len0, int(serializer.data["raward"]), "工作项点检", w.id)

        # 发送微信消息通知 Pulsar
        res = doMoniterPulsarScreen.apply_async(
            (
                w.pid,
                {
                    "status": 9,
                    "localhost": serializer.data.get("wid"),
                    "info": {
                        "name": serializer.data.get("sid"),
                        "message": serializer.data.get("notes"),
                    },
                },
            )
        )
        return Response({"rescode": 200, "resmsg": serializer.data, "inter": x})


class AllinpayPlaceRangeViewSet(viewsets.ModelViewSet):
    __title__ = "场所编码转换"
    __group__ = "门店场所"
    __info__ = {"get": "场所编码转换查询", "post": "场所编码转换创建", "put": "场所编码转换编辑"}
    __doc__ = """
    list:
    <h4>场所编码转换列表</h4>
    retrieve:
    <h4>场所编码转换详情</h4>
    create:
    <h4>场所编码转换创建</h4>
    update:
    <h4>场所编码转换编辑</h4>
    """
    http_method_names = ["get", "post", "put"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BoxPermissions | WeChatPermissions]
    serializer_class = AllinpayPlaceRangeSerializer
    queryset = AllinpayPlaceRange.objects.all()

    # filter_backends = [ListDjangoFilterBackend]
    # filterset_fields = ['pid', 'intetype']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlacedeatListViewSet(viewsets.ModelViewSet):
    __title__ = "门店场所账户有效期"
    __group__ = "门店场所"
    __info__ = {"get": "查询门店场所账户有效期", "post": "创建", "patch": "编辑", "delete": "移除"}
    __doc__ = """	list:
    <h4>门店场所账户有效期列表</h4>
    retrieve:
    <h4>门店场所账户有效期详情</h4>
    create:
    <h4>创建</h4>
    partial_update:
    <h4>编辑</h4>
    delete:
    <h4>移除</h4>"""
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayPlacedeatListSerializer
    queryset = AllinpayPlacedeatList.objects.all()

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["pid"]

    # search_fields = ['phone','email']
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlacedeatLogsViewSet(viewsets.ModelViewSet):
    __title__ = "门店场所账户续期单"
    __group__ = "门店场所"
    __info__ = {
        "get": "查询门店场所账户续期单列表",
        "post": "创建门店场所账户续期单",
        "patch": "审核门店场所账户续期单",
    }
    __doc__ = """	list:
    <h4>门店场所账户续期单列表</h4>
    retrieve:
    <h4>门店场所账户续期单详情</h4>
    create:
    <h4>创建门店场所账户续期单</h4>    
    partial_update:
    <h4>审核门店场所账户续期单</h4>"""
    http_method_names = ["get", "post", "patch"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayPlacedeatLogsSerializer
    queryset = AllinpayPlacedeatLogs.objects.all()

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["pid", "answer"]

    # search_fields = ['phone','email']
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=request.user.id, creatime=timezone.now(), status=0)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.status == 1:
            raise serializers.ValidationError({"id": "对象数据无效"})
        instance.status = 1
        instance.super = request.user.id
        instance.lastime = timezone.now()
        instance.save()
        r, faq = AllinpayPlacedeatList.objects.update_or_create(
            defaults={"deatdate": instance.deatdate}, pid=instance.pid
        )
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


# class ReqsnAllinpayPlacedeatLogsViewSet(viewsets.ModelViewSet):
#     __title__ = "门店场所续期"
#     __group__ = "门店场所"
#     __info__ = {"post": "门店场所续期"}
#     __doc__ = """
#     create:
#     <h4>门店场所续期</h4>"""
#     http_method_names = ["post"]
#     authentication_classes = []
#     permission_classes = [AllPermissions]
#     serializer_class = AllinpayPlacedeatLogsSerializer
#     queryset = AllinpayPlacedeatLogs.objects.all()

#     def create(self, request, *args, **kwargs):
#         serializer = self.serializer_class(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save(answer=request.user.id, creatime=timezone.now())
#         return Response({"rescode": 200, "resmsg": serializer.data})


# 检查视图
filter_views(globals())
